package api

import (
	"encoding/json"
	"pan/common/conf"
	"pan/common/exception"
	"pan/common/log"
	"pan/common/net"
	"pan/common/util"
)

type RefreshTokenRequest struct {
	ExpiresType int    `json:"expirestype"`
	Tokenid     string `json:"tokenid"`
	Userid      string `json:"userid"`
}

type RefreshTokenResponse struct {
	FailRsponse

	Expires int64 `json:"expires"`
}

func RefreshTokenApi(tokenid string, req *RefreshTokenRequest) (*RefreshTokenResponse, error) {
	url := util.PathJoin(conf.GlobalConfig.Url, conf.GlobalConfig.Paths.Refresh)

	if log.IsDebugEnable() {
		bytes, _ := json.Marshal(req)
		log.Debug("refresh token post: ", url, ", token:", tokenid, ", body:", string(bytes))
	}

	resp := &RefreshTokenResponse{}
	if err := net.PostWithToken(url, tokenid, req, resp); err != nil {
		return nil, err
	}

	if log.IsDebugEnable() {
		result, _ := json.Marshal(resp)
		log.Debug("refresh token response: ", string(result))
	}
	if resp.Errcode != 0 {
		return nil, exception.NewExpectError("refresh token failed, %s", resp.FailString())
	}

	conf.GlobalToken.SetExpires(resp.Expires)
	if err := conf.GlobalToken.Save(); err != nil {
		return nil, err
	}
	return resp, nil
}
